<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { fetchGetAllRoles } from '@/service/api';
import { enableStatusOptions } from '@/constants/business';

defineOptions({
  name: 'TenantOperateDrawer'
});

interface Props {
  /** 操作类型 */
  operateType: NaiveUI.TableOperateType;
  /** 编辑行数据 */
  rowData?: ManageApi.TenantManage.Tenant | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增租户',
    edit: '编辑租户'
  };
  return titles[props.operateType];
});

type Model = Pick<
  ManageApi.TenantManage.Tenant,
  'tenantName' | 'tenantPhone' | 'tenantEmail' | 'tenantRoles' | 'status'
>;

const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    tenantName: '',
    tenantPhone: '',
    tenantEmail: '',
    tenantRoles: [],
    status: null
  };
}

type RuleKey = Extract<keyof Model, 'tenantName'>;

const rules: Record<RuleKey, CommonType.WithArray<App.Global.FormRule>> = {
  tenantName: defaultRequiredRule
};

/** 租户角色选项 */
const roleOptions = ref<CommonType.Option<string>[]>([]);

async function getRoleOptions() {
  const { error, data } = await fetchGetAllRoles();

  if (!error) {
    const options = data.map(item => ({
      label: item.roleName,
      value: item.roleCode
    }));

    roleOptions.value = options;
  }
}

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  window.$message?.success('更新成功');
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :mask-closable="false" auto-focus :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="用户名" path="tenantName">
          <NInput v-model:value="model.tenantName" placeholder="请输入租户名" />
        </NFormItem>
        <NFormItem label="手机号" path="tenantPhone">
          <NInput v-model:value="model.tenantPhone" placeholder="请输入手机号" />
        </NFormItem>
        <NFormItem label="邮箱" path="tenantEmail">
          <NInput v-model:value="model.tenantEmail" placeholder="请输入邮箱" />
        </NFormItem>
        <NFormItem label="用户状态" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="item.label" />
          </NRadioGroup>
        </NFormItem>
        <NFormItem label="用户角色" path="roles">
          <NSelect v-model:value="model.tenantRoles" multiple :options="roleOptions" placeholder="请选择租户角色" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">取消</NButton>
          <NButton type="primary" @click="handleSubmit">确认</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
